const common = require("../../utils/common")
const server = require('../../utils/server');
const qiniuUploader = require('../../utils/qiniuUploader');
const app = getApp();
const reg = /^1(3[0-9]|4[01456789]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

function getNearly7Day() {
  let days = []
  var date = new Date()
  for (let i = 0; i <= 24 * 14; i += 24) {
    //今天加上前6天
    let dateItem = new Date(date.getTime() - i * 60 * 60 * 1000) //使用当天时间戳减去以前的时间毫秒（小时*分*秒*毫秒）
    let y = dateItem.getFullYear() //获取年份
    let m = dateItem.getMonth() + 1 //获取月份js月份从0开始，需要+1
    let d = dateItem.getDate() //获取日期
    m = addDate0(m) //给为单数的月份补零
    d = addDate0(d) //给为单数的日期补零
    let valueItem = y + '-' + m + '-' + d //组合
    days.push(valueItem) //添加至数组
  }
  //给日期加0
  function addDate0(time) {
    if (time.toString().length == 1) {
      time = '0' + time.toString()
    }
    return time
  }
  return days
}

Page({

  /**
   * 页面的初始数据
   */
  isSelectStore: false,
  selectTime: [0, 0],
  selectTypeIndex: [0],
  isCansubmit: true,
  data: {
    type: '1',
    menus: [{ val: 1, label: '服务问题' },
    // { val: 2, label: '商品问题' },
    { val: 3, label: '功能反馈' },
    { val: 4, label: '其他问题' }],
    typeName: ['', '服务问题', '商品问题', '功能反馈', '其他问题'],
    goodsQuestions: ['未达预期(外观、口感、价格等)', '包装瑕疵', '变质', '异物', '标识违规', '其他'],
    serviceQuestions: ['未达预期', '服务态度', '送货', '结算', '其他'],
    images: [],
    describe: '',
    function_page: '',
    store_id: '',
    store_name: '',
    arrival_time: '',
    contact_number: '',
    customer_name: '',
    category: '',
    remark: '',
    status_name: '',
    orderList: [],
    isCheck: 0,
    dateList: [],
    timeList: [],
    storeList: [],
    orderStoreList: [],
    showStores: false,
    showTip: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ isCheck }) {
    var options = {
        region: 'ECN',
        uptoken: '',
        uptokenURL: 'https://store0.sungivenplus.com/api/uptoken',
        uptokenFunc: function () { },
        domain: 'https://static.sungivenfood.com',
        key: 'feedback',
        shouldUseQiniuFileName: false
      };
      qiniuUploader.init(options);
    wx.setNavigationBarTitle({
      title: isCheck ? '我的反馈' : '提交意见反馈',
    })
    this.setData({ isCheck: !!isCheck, showTip: !isCheck })
    if (isCheck) {
      wx.getStorage({
        key: 'myFeedback',
        success: res => {
          let { type, images, describe, store_name, arrival_time, contact_number, function_page, remark, status_name, customer_name, category } = res.data
          if (images && images.length) {
            images = images.map(item => {
              return {
                url: item,
                type: ['pdf', 'png', 'jpg', 'jpeg'].indexOf(item.split('.')[3]) != -1 ? 'image' : 'video'
              }
            })
          }
          this.setData({ type, images, describe, store_name, arrival_time, contact_number, function_page, remark, status_name, customer_name, category })
        }
      })
      return
    }
    // 获取用户下单门店
    this.getStore()
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let timeList = [], dateList = getNearly7Day()
    for (let i = 6; i < 23; i++) {
      timeList.push(`${i}:00 - ${i}:30`)
      timeList.push(`${i}:30 - ${i + 1}:00`)
    }
    this.setData({
      timeList, dateList,
      selectTime: [0, 0],
    })
  },

  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    wx.removeStorage({
      key: 'myFeedback',
    })
  },

  // 上传图片视频
  chooseMedia() {
    common.chooseMedia(this, this.data.images, 6, 2, 20)
  },

  // 图片视频预览
  previewMedia(e) {
    const { current } = e.currentTarget.dataset;
    common.previewMedia(this.data.images, current)
  },

  // 校验手机号
  checkTel(e) {
    let val = e.detail.value
    if (val && !reg.test(val)) {
      common.showToast('手机号格式有误')
      return
    }
  },

  // 查找门店
  storeInput(e) {
    const { value } = e.detail
    this.data.store_id = ''
    this.isSelectStore = false
    this.setData({
      store_name: value,
    })
    // 无输入值不搜索
    if (!value) {
      this.setData({
        showStores: true,
        storeList: this.data.orderStoreList
      })
      return
    }
    if (this.isSearch) return
    this.isSearch = true
    common.getStoreByLaLon(value).then(res => {
      const { data, errno } = res
      if (errno == '0') {
        let list = data.filter(item => item.name.includes(value)).map(item => ({
          store_id: item.store_id,
          name: item.name
        }))
        this.setData({
          showStores: !!list.length,
          storeList: list
        })
      }
      this.isSearch = false
    })
  },

  // 获取用户下单门店
  getStore() {
    server.postJSON(common.storePath + "feedback/getstore", {}, res => {
      const { errno, data } = res.data;
      this.isSearch = false
      if (errno == '0') {
        this.setData({
          showStores: !this.data.store_name && this.data.isStoreFocus && data.length,
          orderStoreList: data,
          storeList: data
        })
      }
    })
  },

  storeFocus() {
    this.data.isStoreFocus = true
    const { store_name, storeList, orderStoreList } = this.data
    if (store_name && storeList.length) {
      this.setData({
        showStores: true,
        storeList: storeList,
      })
    }
    if (!store_name && orderStoreList.length) {
      this.setData({
        showStores: true,
        storeList: orderStoreList,
      })
    }
  },

  hideStores() {
    this.setData({
      showStores: false,
    })
    if (!this.data.store_id && !this.data.isCheck) this.setData({ store_name: '' })
  },

  storeBlur() {
    if (!this.isSelectStore && this.data.store_name && !this.data.showStores) {
      this.setData({ store_name: '' })
      this.data.store_id = ''
      return
    }
    if (!this.data.store_name) this.setData({ showStores: false })
  },

  selectStore(e) {
    const { id, name } = e.currentTarget.dataset
    this.isSelectStore = true
    this.data.store_id = id
    this.setData({
      store_name: name,
      showStores: false,
    })
  },

  inputHandle(e) {
    this.setData({
      [e.currentTarget.dataset.param]: e.detail.value
    })
  },

  showPop(e) {
    if (this.data.isCheck) return
    this.selectComponent(`#${e.currentTarget.dataset.param}`).showPop()
  },

  bindTimeChange(e) {
    this.selectTime = e.detail.value
  },

  timeConfirm() {
    const { dateList, timeList } = this.data
    this.setData({
      arrival_time: `${dateList[this.selectTime[0]]} ${timeList[this.selectTime[1]]}`
    })
    this.selectComponent('#time').hidePop()
  },

  bindTypeChange(e) {
    this.selectTypeIndex = e.detail.value[0]
  },

  typeConfirm() {
    const type = this.data.menus[this.selectTypeIndex].val
    this.setData({
      type,
      showTip: type == 1 || type == 4
    })
    if (type == 1 || type == 2) this.getStore()
    this.selectComponent('#type').hidePop()
  },

  selectQuestion(e) {
    this.setData({
      category: e.currentTarget.dataset.item
    })
    this.selectComponent('#question').hidePop()
  },

  addFeedback() {
    this.setData({ showStores: false })
    const { images, describe, contact_number, type, store_id, store_name, category, arrival_time } = this.data
    if (!type) {
      common.showToast('请选择反馈主题')
      return
    }
    if (!describe) {
      common.showToast('相关描述不能为空')
      return
    }
    if (type == 1 || type == 2 || type == 4) {
      if (!store_name) {
        common.showToast('门店名称不能为空')
        return
      }
      if (!store_id) {
        this.setData({ store_name: '' })
        common.showToast('请输入关键词搜索并选择门店')
        return
      }
      if (type != 4 && !category) {
        common.showToast('请选择问题类型')
        return
      }
      if (!arrival_time) {
        common.showToast('请选择消费时间')
        return
      }
    }
    if (!contact_number) {
      common.showToast('联系电话不能为空')
      return
    }
    if (contact_number && !reg.test(contact_number)) {
      common.showToast('手机号格式有误')
      return
    }
    if (!this.isCansubmit) return
    this.isCansubmit = false
    // 向七牛云上传
    let i = 0, uploadImages = []
    common.showLoading('正在提交...')
    if (images.length) {
      const { envVersion } = wx.getAccountInfoSync().miniProgram
      const fileName = envVersion == 'release' ? 'feedback' : 'feedback_test'
      let flag = false
      images.forEach(({ url }, index) => {
        qiniuUploader.upload(url, res => {
          flag = flag || res.fileURL.indexOf('undefined') != -1
          uploadImages[index] = res.fileURL
          i += 1
          // 图片全部上传完再提交
          if (i == images.length) {
            if (uploadImages.length != images.length || flag) {
              common.showToast('部分文件上传失败，请稍后重试')
              this.isCansubmit = true
              return
            }
            this.submitForm(uploadImages)
          }
        }, error => {
          common.showToast('error: ' + error);
          this.isCansubmit = true
        }, {
          region: app.theme.qiniuRegion,
          key: `${fileName}/${parseInt(new Date().getTime())}.${url.split('.')[1]}`, // 自定义上传文件名
        })
      })
      return
    }
    this.submitForm()
  },

  submitForm(uploadImages = []) {
    const { type, describe, store_id, store_name, arrival_time, contact_number, function_page, category, customer_name } = this.data
    const params = {
      type, describe, contact_number, customer_name,
      scene: app.globalData.sceneId
    }
    if (type == 1) {
      params.store_id = store_id
      params.store_name = store_name
      params.category = category
      params.arrival_time = arrival_time
    }
    if (type == 3) {
      params.images = uploadImages
      params.function_page = function_page
    }
    if (type == 4) {
      params.images = uploadImages
      params.store_id = store_id
      params.store_name = store_name
      params.arrival_time = arrival_time
    }
    server.postJSON(common.storePath + 'feedback/add', params, res => {
      const { errno, errmsg } = res.data;
      if (errno == '0') {
        common.showToast('提交成功')
        setTimeout(() => {
          wx.redirectTo({ url: 'records' })
        }, 500);
      } else {
        common.showErrorToast(errmsg);
      }
      setTimeout(() => {
        this.isCansubmit = true
      }, 500);
    })
  },

  // 删除图片视频
  delMedia(e) {
    this.data.images.splice(e.currentTarget.dataset.index, 1)
    this.setData({ images: this.data.images })
  },

  hidePop() {
    this.setData({
      showTip: false
    })
  },

  toOrder() {
    common.navigateTo({
      url: '/pages/order/orderIndex',
    })
  }

})